package com.wad.manager.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.wad.manager.mapper.CategoryMapper;
import com.wad.vo.product.CategoryExcelVo;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wad
 * @date 2023/12/07 11:06
 * @project e-commerce
 **/
public class ExcelListener<T> implements ReadListener<T> {

    private CategoryMapper categoryMapper;

    private static final int BATCH_COUNT=100;

    /*
    缓存的数据集合
     */
    private List<T> cacheDataList= ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    //通过构造方法传递mapper
    public ExcelListener(CategoryMapper categoryMapper){
        this.categoryMapper=categoryMapper;
    }

    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        //每行数据的对象放到缓存集合中
        cacheDataList.add(t);
        if (cacheDataList.size()>=BATCH_COUNT){
            //调用方法添加到数据库中
            saveData();
            //清空缓存
            cacheDataList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //调用saveData方法将剩下不足BATCH_SIZE的数据进行插入
        saveData();
    }

    private void saveData() {
        categoryMapper.batchInsert((List<CategoryExcelVo>) cacheDataList);
    }
}
